package viewcontroller;

import utils.ServiceHandler;
import model.Product;

import com.example.lastprojectbeautiplus.R;
import com.google.gson.Gson;

import adapter.ProductGridViewAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class ProductListByCategory extends Fragment {
	public ProductListByCategory() {}
	private GridView gvCategory;
	private ProductGridViewAdapter pAdapter;
	private Product[] listProduct;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.fragment_product_by_cate, container, false);
		Bundle extras = getActivity().getIntent().getExtras();
		int target = extras.getInt("FromCateView");
		String urlProductByCate = "http://services-beautyplus.rhcloud.com/rest/ProductServices/ProByCate/" + target;
		new getProductList(urlProductByCate).execute();
		gvCategory = (GridView) rootView.findViewById(R.id.gvCategory);
		gvCategory.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), SlideMenu.class);
				intent.putExtra("FromProductList", listProduct[position].getProductID());
				getActivity().startActivity(intent);
			}
		});
		return rootView;
	}
	private class getProductList extends AsyncTask<Void, Void, Void>{
		private String url;
		private String responseProductList;
		public getProductList(String url) {
			// TODO Auto-generated constructor stub
			this.url = url;
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ServiceHandler sh = new ServiceHandler();
			responseProductList = sh.executeGetRequest(url);
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Gson myGson = new Gson();
			listProduct = myGson.fromJson(responseProductList, Product[].class);
			pAdapter = new ProductGridViewAdapter(getActivity(), R.layout.gridview_product_item, listProduct);
			gvCategory.setAdapter(pAdapter);
			
		}
	}
}
